package com.simple.dispatcher.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.simple.dispatcher.service.DispatcherService;
import com.simple.dispatcher.service.MyWeiboService;
import com.simple.dispatcher.servlet.utils.JSONUtils;
import com.simple.dispatcher.servlet.utils.RequestParamUtils;

@Controller
public class DispatchMsgServlet {

	@Autowired
	private DispatcherService dispatcherService;
	
	@Autowired
	private MyWeiboService weiboService; 

	@RequestMapping("/dispatch.do")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		
		String srcUrl = RequestParamUtils.getStringValue(req, "srcUrl", "http://job.xjtu.edu.cn/jobs/31373");
		String abstractMsg = RequestParamUtils.getStringValue(req, "abstract", "华为2012年应届毕业生招聘正式启动： 加入华为  大有可为" + System.currentTimeMillis());
//		String meta = RequestParamUtils.getStringValue(req, "meta", "{\"industry\": [\"计算机\"], \"jobtitle\": [\"软件研发\"], \"location\": [\"西安\"], \"salary\": 5000, \"company\": \"华为\", \"type\": [\"全职\"]}");
		
		String[] locations = RequestParamUtils.getStringValues(req, "location", null);
		String[] jobtitles = RequestParamUtils.getStringValues(req, "jobtitle", null);
		String[] industries = RequestParamUtils.getStringValues(req, "industry", null);
		long salary = RequestParamUtils.getLongValue(req, "salary", 0L);
		String company = RequestParamUtils.getStringValue(req, "company", "");
		String[] types = RequestParamUtils.getStringValues(req, "job_type", null);
		
		String meta = JSONUtils.generateJobMetaOrFilter(industries, jobtitles, locations, salary, company, types, true);
		
		long weiboId = weiboService.publishWeiBo(abstractMsg, srcUrl);
		
		if(StringUtils.isNotEmpty(meta) && weiboId != 0L){
			dispatcherService.dispatch(weiboId, meta);
			resp.setStatus(HttpServletResponse.SC_OK);
			return;
		}
		
		resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
	}
}
